import {
    ParameterInformation,
    SignatureHelp,
    SignatureInformation
} from "vscode-languageserver";
import { t } from "./analysis";
import {
    getFinalSymbol,
    getNodeWithPathAtPosition,
    getSymbolRanks,
    makeDocumentFromSymbol,
    makeFullParameterDetailFromSymbol
} from "./util";


export async function provideSignatureHelp(source: t.SourceFile, position: number): Promise<SignatureHelp | null> {
    const nodeResult = getNodeWithPathAtPosition(source, position);
    if (!nodeResult.path.callExpression) {
        return null;
    }
    let symbol = getFinalSymbol(nodeResult.path.callExpression.callee);
    if (!symbol || !symbol.is(t.SymbolKind.functionLike)) {
        return null;
    }

    let params: string[] = [];
    let paramInfos: ParameterInformation[] = [];
    for (const param of symbol.parameters) {
        const content = makeFullParameterDetailFromSymbol(param);
        params.push(content);
        paramInfos.push({ label: content });
    }

    let fullNote = `${symbol.name}(${params.join(", ")}): ${symbol.type.name}${getSymbolRanks(symbol)}`;
    const signatureInfo: SignatureInformation = {
        label: fullNote,
        documentation: {
            kind: "markdown",
            value: makeDocumentFromSymbol(symbol)
        },
        parameters: paramInfos
    };

    signatureInfo.activeParameter = nodeResult.path.callExpression.arguments.length;
    if (nodeResult.path.callExpression.callByDot && symbol.is(t.SymbolKind.function)) {
        signatureInfo.activeParameter++;
    }

    return {
        signatures: [ signatureInfo ]
    };
}
